package services

import (
	"errors"
	"sync"
)

// privateConfig 需保护的配置
var privateConfig map[string]any

// SafeConfig 封装资源配置，加锁（装饰者模式）
type SafeConfig struct {
	resource map[string]any
	lock     sync.Mutex
}

// UnSafeSet 非线程安全的设置
func (s *SafeConfig) UnSafeSet(key string, value any) (result any) {
	s.resource[key] = value
	return value
}

// Set 线程安全的设置
func (s *SafeConfig) Set(key string, value any) (result any) {
	s.lock.Lock()
	defer s.lock.Unlock()

	s.resource[key] = value
	return value
}

func (s *SafeConfig) Get(key string) (value any, err error) {
	s.lock.Lock()
	defer s.lock.Unlock()
	value, ok := s.resource[key]

	if !ok {
		err = errors.New(key + " not exist")
	}
	return
}

func (s *SafeConfig) UnafeGet(key string) (value any, err error) {
	value, ok := s.resource[key]

	if !ok {
		err = errors.New(key + " not exist")
	}
	return
}
